#pragma once

#include <iostream>
#include <string>
#include <cerrno>
#include <cstring>
#include <cstdlib>
#include <functional>
#include <unordered_map>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <pthread.h>
#include <functional>
#include <map>
#include "log.hpp"
#include "InetAddr.hpp"
#include "nocopy.hpp"
#include "Comm.hpp"
#include "pthreadpoul.hpp"
using callback_t = function<void(int, InetAddr &)>;
using task_t = function<void()>;
using namespace std;
const static int default_backlog = 5;
class TcpServer : public nocopy
{
public:
    TcpServer(uint16_t port) : _port(port)
    {
    }
    void Init()
    {
        _listensock = socket(AF_INET, SOCK_STREAM, 0);
        if (_listensock < 0)
        {
            lg.massage(Fatal, "create socket errno,errno code:%d,error string:%s\n", errno, strerror(errno));
            exit(Fatal);
        }
        lg.massage(Debug, "create socket success, sockfd: %d\n", _listensock);
        struct sockaddr_in local;
        memset(&local, 0, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(_port);
        local.sin_addr.s_addr = 0;
        if (bind(_listensock, (struct sockaddr *)&local, sizeof(local)) != 0)
        {
            lg.massage(Fatal, "create bind errno,errno code:%d,error string:%s\n", errno, strerror(errno));
            exit(Fatal);
        }
        lg.massage(Debug, "create bind success, sockfd: %d\n", _listensock);
        if (listen(_listensock, default_backlog) != 0)
        {
            lg.massage(Fatal, "listen errno,errno code:%d,error string:%s\n", errno, strerror(errno));
            exit(Fatal);
        }
        lg.massage(Debug, "listen success, sockfd: %d\n", _listensock);
        funcs.insert(std::make_pair("defaultService", std::bind(&TcpServer::DefaultService, this, std::placeholders::_1, std::placeholders::_2)));
        Threadpool<task_t>::GetInstance()->start();
    }
    void Service(int fd)
    {
        char buffer[1024];
        while (true)
        {
            ssize_t n = read(fd, buffer, sizeof(buffer));
            if (n > 0)
            {
                buffer[n] = 0;
                cout << "client say:" << buffer << endl;
                string echo_string = "server echo#";
                echo_string += buffer;
                write(fd, echo_string.c_str(), echo_string.size());
            }
            else if (n == 0)
            {
                lg.massage(Info, "client quit...\n");
                break;
            }
            else
            {
                lg.massage(Error, "read socket error, errno code: %d, error string: %s\n", errno, strerror(errno));
                break;
            }
        }
    }
    void server()
    {
    }
    void Start()
    {
        _isrunning = true;
        signal(SIGCHLD, SIG_IGN);
        while(_isrunning)
        {
        struct sockaddr_in peer;
        socklen_t len = sizeof(peer);
        int sockfd = accept(_listensock, CONY(&peer), &len);
        if (sockfd < 0)
        {
            lg.massage(Warning, "accept socket error, errno code: %d, error string: %s\n", errno, strerror(errno));
        }
        lg.massage(Debug, "accept success, get n new sockfd: %d\n", sockfd);
        // Service(sockfd);
        // close(sockfd);
        // server();
        task_t t = bind(&TcpServer::Routine, this, sockfd, InetAddr(peer));
        Threadpool<task_t>::GetInstance()->push(t);
        }
    }
    // void Routine(int sockfd, InetAddr &addr)
    // {
    //     cout<<"进入Rountine"<<endl;
    //     funcs["DefaultService"](sockfd, addr);
    //     string type = Read(sockfd);
    //     if (type == "ping")
    //         funcs[type](sockfd, addr);
    //     else if (type == "translate")
    //         funcs[type](sockfd, addr);
    //     else if (type == "transform")
    //         funcs[type](sockfd, addr);
    //     else
    //     {
    //     }

    //     close(sockfd);
    // }
    void Routine(int sockfd, InetAddr addr)
    {
        funcs["defaultService"](sockfd, addr);
        std::string type = Read(sockfd);
        lg.massage(Debug, "%s select %s\n", addr.PrintDebug().c_str(), type.c_str());
        if(type == "ping")
            funcs[type](sockfd, addr);
        else if(type == "translate")
            funcs[type](sockfd, addr);
        else if(type == "transform")
            funcs[type](sockfd, addr);
        else
        {
            string error="没有这个选项，你个沙雕";
            write(sockfd,error.c_str(),error.size());
        }

        close(sockfd);
    }
    string Read(int sockfd)
    {
        cout<<"进入Read"<<endl;
        char buffer[64];
        int n = read(sockfd, buffer, sizeof(buffer) - 1);
        if (n > 0)
        {
            buffer[n] = 0;
        }
        else if (n == 0) // read如果返回值是0，表示读到了文件结尾(对端关闭了连接！)
        {
            lg.massage(Info, "client quit...\n");
        }
        else
        {
            lg.massage(Error, "read socket error, errno code: %d, error string: %s\n", errno, strerror(errno));
        }
        return buffer;
    }
    void RegisterFunc(const std::string &name, callback_t func)
    {
        funcs[name] = func;
    }
    void DefaultService(int sockfd, InetAddr &addr)
    {
         cout<<"进入DefaultService"<<endl;
        ssize_t n=2;
        (void)addr;
        string server_list;
        for (auto data : funcs)
        {
            server_list += "[";
            server_list += data.first;
            server_list += "]";
        }
         n=write(sockfd, server_list.c_str(), server_list.size());
        cout<<n<<endl;
    }
    ~TcpServer()
    {
    }

private:
    uint16_t _port;
    int _listensock;
    bool _isrunning;
    std::unordered_map<std::string, callback_t> funcs;
};